{% extends "base.html" %}

{% block title %}选课管理 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .tabs {
        display: flex;
        gap: 1rem;
        margin-bottom: 1.5rem;
        border-bottom: 2px solid #e0e0e0;
    }
    
    .tab {
        padding: 0.75rem 1.5rem;
        cursor: pointer;
        border: none;
        background: none;
        font-size: 1rem;
        color: #7f8c8d;
        transition: all 0.3s;
        border-bottom: 3px solid transparent;
        margin-bottom: -2px;
    }
    
    .tab.active {
        color: #3498db;
        border-bottom-color: #3498db;
        font-weight: 600;
    }
    
    .tab-content {
        display: none;
    }
    
    .tab-content.active {
        display: block;
    }
    
    .search-bar {
        display: flex;
        gap: 1rem;
        margin-bottom: 1.5rem;
        flex-wrap: wrap;
    }
    
    .search-bar input, .search-bar select {
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        font-size: 0.9rem;
    }
    
    .course-card {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        margin-bottom: 1rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: all 0.3s;
    }
    
    .course-card:hover {
        box-shadow: 0 4px 16px rgba(0,0,0,0.15);
    }
    
    .course-header {
        display: flex;
        justify-content: space-between;
        align-items: start;
        margin-bottom: 1rem;
    }
    
    .course-title {
        flex: 1;
    }
    
    .course-title h3 {
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }
    
    .course-code {
        color: #7f8c8d;
        font-size: 0.9rem;
    }
    
    .course-info {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 1rem;
        margin-bottom: 1rem;
        padding: 1rem;
        background: #f8f9fa;
        border-radius: 4px;
    }
    
    .info-item {
        font-size: 0.9rem;
    }
    
    .info-label {
        color: #7f8c8d;
        margin-bottom: 0.25rem;
    }
    
    .info-value {
        color: #2c3e50;
        font-weight: 500;
    }
    
    .course-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .badge-full {
        background: #f8d7da;
        color: #721c24;
    }
    
    .badge-available {
        background: #d4edda;
        color: #155724;
    }
    
    .badge-enrolled {
        background: #d1ecf1;
        color: #0c5460;
    }
    
    .badge-completed {
        background: #d4edda;
        color: #155724;
    }
    
    .badge-dropped {
        background: #f8d7da;
        color: #721c24;
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom:1.5rem;">选课管理</h2>

<div class="tabs">
    <button class="tab active" onclick="switchTab('available')">可选课程</button>
    <button class="tab" onclick="switchTab('enrolled')">已选课程</button>
</div>

<!-- 可选课程 -->
<div id="available-tab" class="tab-content active">
    <div class="search-bar">
        <input type="text" id="search-available" placeholder="搜索课程名称/代码..." style="flex:1;min-width:250px;">
        <select id="filter-department">
            <option value="">全部院系</option>
        </select>
        <select id="filter-semester">
            <option value="">全部学期</option>
        </select>
        <button class="btn btn-primary" onclick="searchAvailableCourses()">搜索</button>
    </div>
    
    <div id="available-courses"></div>
    <div id="available-pagination" style="text-align:center;margin-top:1rem;"></div>
</div>

<!-- 已选课程 -->
<div id="enrolled-tab" class="tab-content">
    <div id="enrolled-courses"></div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentTab = 'available';
    let currentPage = 1;
    
    function switchTab(tab) {
        currentTab = tab;
        
        // 更新tab样式
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        
        event.target.classList.add('active');
        document.getElementById(`${tab}-tab`).classList.add('active');
        
        // 加载对应数据
        if (tab === 'available') {
            loadAvailableCourses();
        } else {
            loadEnrolledCourses();
        }
    }
    
    async function loadAvailableCourses(page = 1) {
        try {
            const search = document.getElementById('search-available').value;
            const department = document.getElementById('filter-department').value;
            const semester = document.getElementById('filter-semester').value;
            
            const params = new URLSearchParams({
                page: page,
                per_page: 10
            });
            if (search) params.append('search', search);
            if (department) params.append('department', department);
            if (semester) params.append('semester', semester);
            
            const data = await apiRequest(`/student/available-courses?${params.toString()}`);
            
            if (data.success) {
                renderAvailableCourses(data.data);
                renderPagination(data.pagination);
                currentPage = page;
            }
        } catch (error) {
            showAlert('加载课程失败: ' + error.message, 'error');
        }
    }
    
    function renderAvailableCourses(courses) {
        const container = document.getElementById('available-courses');
        
        if (courses.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:#7f8c8d;padding:2rem;">暂无可选课程</p>';
            return;
        }
        
        container.innerHTML = courses.map(course => `
            <div class="course-card">
                <div class="course-header">
                    <div class="course-title">
                        <h3>${course.name}</h3>
                        <div class="course-code">${course.code} | ${course.credits} 学分</div>
                    </div>
                    <div>
                        ${course.is_enrolled ? '<span class="badge badge-enrolled">已选</span>' : 
                          course.is_full ? '<span class="badge badge-full">已满</span>' : 
                          '<span class="badge badge-available">可选</span>'}
                    </div>
                </div>
                
                <div class="course-info">
                    <div class="info-item">
                        <div class="info-label">院系</div>
                        <div class="info-value">${course.department || '-'}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">学期</div>
                        <div class="info-value">${formatSemester(course)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">授课教师</div>
                        <div class="info-value">${course.instructor_name}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">选课人数</div>
                        <div class="info-value">${course.enrollment_count}${course.max_students ? '/' + course.max_students : ''}</div>
                    </div>
                </div>
                
                <p style="color:#7f8c8d;font-size:0.9rem;margin-bottom:1rem;">${course.description || '暂无描述'}</p>
                
                <div class="course-actions">
                    ${!course.is_enrolled && !course.is_full ? 
                        `<button class="btn btn-primary" onclick="enrollCourse(${course.id})">选课</button>` : 
                        course.is_enrolled ? 
                        `<button class="btn btn-secondary" disabled>已选</button>` :
                        `<button class="btn btn-secondary" disabled>已满</button>`
                    }
                    <a href="/courses/${course.id}" class="btn btn-secondary" target="_blank">查看详情</a>
                </div>
            </div>
        `).join('');
    }
    
    function renderPagination(pagination) {
        const container = document.getElementById('available-pagination');
        
        if (pagination.pages <= 1) {
            container.innerHTML = '';
            return;
        }
        
        let html = '<div style="display:flex;gap:0.5rem;justify-content:center;align-items:center;">';
        
        if (pagination.page > 1) {
            html += `<button class="btn btn-secondary" onclick="loadAvailableCourses(${pagination.page - 1})">上一页</button>`;
        }
        
        html += `<span style="color:#7f8c8d;">第 ${pagination.page} / ${pagination.pages} 页</span>`;
        
        if (pagination.page < pagination.pages) {
            html += `<button class="btn btn-secondary" onclick="loadAvailableCourses(${pagination.page + 1})">下一页</button>`;
        }
        
        html += '</div>';
        container.innerHTML = html;
    }
    
    async function loadEnrolledCourses() {
        try {
            const data = await apiRequest('/student/my-courses');
            
            if (data.success) {
                renderEnrolledCourses(data.data);
            }
        } catch (error) {
            showAlert('加载已选课程失败: ' + error.message, 'error');
        }
    }
    
    async function renderEnrolledCourses(courses) {
        const container = document.getElementById('enrolled-courses');
        
        if (courses.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:#7f8c8d;padding:2rem;">暂无已选课程</p>';
            return;
        }
        
        container.innerHTML = courses.map(course => `
            <div class="course-card">
                <div class="course-header">
                    <div class="course-title">
                        <h3>${course.name}</h3>
                        <div class="course-code">${course.code} | ${course.credits} 学分</div>
                    </div>
                    <div>
                        ${course.enrollment_status === 'enrolled' ? '<span class="badge badge-enrolled">在读</span>' : 
                          course.enrollment_status === 'completed' ? '<span class="badge badge-completed">已完成</span>' :
                          '<span class="badge badge-dropped">已退课</span>'}
                    </div>
                </div>
                
                <div class="course-info">
                    <div class="info-item">
                        <div class="info-label">院系</div>
                        <div class="info-value">${course.department || '-'}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">授课教师</div>
                        <div class="info-value">${course.instructor_name}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">选课日期</div>
                        <div class="info-value">${course.enrollment_date || '-'}</div>
                    </div>
                </div>
                
                ${course.score !== null || course.midterm_score !== null || course.final_score !== null ? `
                <div style="background:#f8f9fa;padding:1rem;border-radius:4px;margin-bottom:1rem;">
                    <h4 style="color:#2c3e50;margin:0 0 0.75rem 0;font-size:1rem;">📊 成绩详情</h4>
                    <div class="course-info" style="margin:0 0 0.75rem 0;">
                        <div class="info-item">
                            <div class="info-label">总评成绩</div>
                            <div class="info-value" style="color:${course.score >= 60 ? '#27ae60' : '#e74c3c'};font-weight:600;">
                                ${course.score !== null ? course.score.toFixed(2) + ' (' + (course.letter_grade || '-') + ')' : '-'}
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">平时成绩</div>
                            <div class="info-value">
                                ${course.midterm_score !== null ? course.midterm_score.toFixed(2) : '-'}
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">考试成绩</div>
                            <div class="info-value">
                                ${course.final_score !== null ? course.final_score.toFixed(2) : '-'}
                            </div>
                        </div>
                    </div>
                    ${course.score !== null ? `
                    <div id="rank-info-${course.id}" style="border-top:1px solid #e0e0e0;padding-top:0.75rem;margin-top:0.5rem;">
                        <div style="text-align:center;color:#7f8c8d;font-size:0.9rem;">
                            <span class="loading-spinner">加载排名信息...</span>
                        </div>
                    </div>
                    ` : ''}
                </div>
                ` : ''}
                
                ${course.attendance_rate !== null || course.total_classes !== null ? `
                <div style="background:#f8f9fa;padding:1rem;border-radius:4px;margin-bottom:1rem;">
                    <h4 style="color:#2c3e50;margin:0 0 0.75rem 0;font-size:1rem;">📅 出勤情况</h4>
                    <div class="course-info" style="margin:0;">
                        <div class="info-item">
                            <div class="info-label">出勤率</div>
                            <div class="info-value" style="color:${course.attendance_rate >= 70 ? '#27ae60' : course.attendance_rate >= 60 ? '#f39c12' : '#e74c3c'};font-weight:600;">
                                ${course.attendance_rate !== null ? course.attendance_rate.toFixed(1) + '%' : '-'}
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">总课时</div>
                            <div class="info-value">
                                ${course.total_classes !== null ? course.total_classes + '次' : '-'}
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">实际出勤</div>
                            <div class="info-value">
                                ${course.attended !== null ? course.attended + '次' : '-'}
                            </div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">缺勤</div>
                            <div class="info-value" style="color:#e74c3c;">
                                ${course.total_classes !== null && course.attended !== null ? (course.total_classes - course.attended) + '次' : '-'}
                            </div>
                        </div>
                    </div>
                </div>
                ` : ''}
                
                <p style="color:#7f8c8d;font-size:0.9rem;margin-bottom:1rem;">${course.description || '暂无描述'}</p>
                
                <div class="course-actions">
                    ${course.enrollment_status === 'enrolled' ? 
                        `<button class="btn btn-danger" onclick="dropCourse(${course.id}, '${course.name}')">退课</button>` : ''}
                    <a href="/courses/${course.id}" class="btn btn-secondary" target="_blank">查看详情</a>
                </div>
            </div>
        `).join('');
        
        // 异步加载每个课程的排名信息
        for (const course of courses) {
            if (course.score !== null && course.id) {
                loadCourseRank(course.id);
            }
        }
    }
    
    async function loadCourseRank(courseId) {
        try {
            const data = await apiRequest(`/student/course/${courseId}/rank`);
            
            if (data.success && data.data) {
                const rank = data.data;
                const container = document.getElementById(`rank-info-${courseId}`);
                
                if (container) {
                    const percentileColor = 
                        rank.percentile >= 80 ? '#27ae60' :
                        rank.percentile >= 60 ? '#3498db' :
                        rank.percentile >= 40 ? '#f39c12' :
                        '#e74c3c';
                    
                    container.innerHTML = `
                        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:0.75rem;font-size:0.9rem;">
                            <div style="text-align:center;">
                                <div style="color:#7f8c8d;font-size:0.85rem;margin-bottom:0.25rem;">班级排名</div>
                                <div style="color:${percentileColor};font-weight:600;font-size:1.1rem;">
                                    第 ${rank.rank} 名
                                </div>
                                <div style="color:#95a5a6;font-size:0.8rem;">共 ${rank.total_students} 人</div>
                            </div>
                            <div style="text-align:center;">
                                <div style="color:#7f8c8d;font-size:0.85rem;margin-bottom:0.25rem;">成绩百分位</div>
                                <div style="color:${percentileColor};font-weight:600;font-size:1.1rem;">
                                    前 ${rank.percentile}%
                                </div>
                                <div style="color:#95a5a6;font-size:0.8rem;">${rank.rank_description}</div>
                            </div>
                            <div style="text-align:center;">
                                <div style="color:#7f8c8d;font-size:0.85rem;margin-bottom:0.25rem;">班级平均分</div>
                                <div style="color:#2c3e50;font-weight:600;font-size:1.1rem;">
                                    ${rank.average_score}
                                </div>
                                <div style="color:${rank.score_diff >= 0 ? '#27ae60' : '#e74c3c'};font-size:0.8rem;">
                                    ${rank.score_diff >= 0 ? '+' : ''}${rank.score_diff}
                                </div>
                            </div>
                        </div>
                    `;
                }
            }
        } catch (error) {
            // 排名加载失败，显示提示
            const container = document.getElementById(`rank-info-${courseId}`);
            if (container) {
                container.innerHTML = `
                    <div style="text-align:center;color:#95a5a6;font-size:0.85rem;">
                        排名信息暂不可用
                    </div>
                `;
            }
        }
    }
    
    async function enrollCourse(courseId) {
        if (!confirm('确定要选择这门课程吗？')) return;
        
        try {
            const data = await apiRequest(`/student/enroll/${courseId}`, {
                method: 'POST'
            });
            
            if (data.success) {
                showAlert('选课成功！', 'success');
                loadAvailableCourses(currentPage);
            }
        } catch (error) {
            showAlert('选课失败: ' + error.message, 'error');
        }
    }
    
    async function dropCourse(courseId, courseName) {
        if (!confirm(`确定要退选《${courseName}》吗？退课后成绩记录将保留但状态会变为"已退课"。`)) return;
        
        try {
            const data = await apiRequest(`/student/drop/${courseId}`, {
                method: 'DELETE'
            });
            
            if (data.success) {
                showAlert('退课成功', 'success');
                loadEnrolledCourses();
            }
        } catch (error) {
            showAlert('退课失败: ' + error.message, 'error');
        }
    }
    
    function searchAvailableCourses() {
        loadAvailableCourses(1);
    }
    
    // 加载院系和学期选项
    async function loadFilters() {
        try {
            const data = await apiRequest('/student/available-courses?per_page=1000');
            if (data.success) {
                const departments = new Set();
                const semesters = new Set();
                
                data.data.forEach(course => {
                    if (course.department) departments.add(course.department);
                    if (course.semester) semesters.add(course.semester);
                });
                
                const deptSelect = document.getElementById('filter-department');
                departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept;
                    option.textContent = dept;
                    deptSelect.appendChild(option);
                });
                
                const semSelect = document.getElementById('filter-semester');
                semesters.forEach(sem => {
                    const option = document.createElement('option');
                    option.value = sem;
                    option.textContent = sem;
                    semSelect.appendChild(option);
                });
            }
        } catch (error) {
            console.error('加载筛选项失败:', error);
        }
    }
    
    // 页面加载
    window.addEventListener('DOMContentLoaded', () => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'student') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        loadFilters();
        loadAvailableCourses();
    });
</script>
{% endblock %}











